package io.github.liuyuhao412.manager.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import io.github.liuyuhao412.manager.entity.User;
import io.github.liuyuhao412.manager.service.TokenService;
import io.github.liuyuhao412.manager.service.UserService;

@Component
@Order(2)
public class JwtAuthenticationFilter extends OncePerRequestFilter {

	@Autowired
	private TokenService tokenService;

	@Autowired
	private UserService userService;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		String authHeader = request.getHeader("Authorization");

		if (authHeader != null && authHeader.startsWith("Bearer ")) {
			String token = authHeader.substring(7);
			try {
				Integer userId = tokenService.getUserIdFromToken(token);
				User user = userService.getUserById(userId);
				// 用户存在且状态为正常
				if (user != null && user.getStatus() != null && user.getStatus() == 1) {

					// 根据 role 设置权限
					List<GrantedAuthority> authorities = new ArrayList<>();
					if ("admin".equalsIgnoreCase(user.getRole())) {
						authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
					} else if ("user".equalsIgnoreCase(user.getRole())) {
						authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
					}

					UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,
							null, authorities);
					SecurityContextHolder.getContext().setAuthentication(authentication);
				}

			} catch (Exception e) {
				// token 无效或异常，返回 401
				response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
				return;
			}
		}

		filterChain.doFilter(request, response);
	}
}
